<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>韭研公社实时文章</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Arial, sans-serif;
            margin: 2px;
            background-color: #0a0a0a;
            padding-top:0px;
        }

        .container {
            display: grid;
            gap: 2px;
        }

        .category-bar {
            display: flex;
            gap: 2px;
            margin-bottom: 4px;
            padding: 2px;
            background: #1a1a1a;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.25);
            flex-wrap: wrap;
            border: 1px solid #2d2d2d;
        }

        .category-btn {
            font-size: 16px;
            font-family: "Microsoft YaHei", sans-serif;
            padding: 4px 6px;
            border: 1px solid #3a3a3a;
            border-radius: 20px;
            background: #2a2a2a;
            color: #9e9e9e;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: 500;
            flex-shrink: 0;
        }

        .category-btn.active {
            font-size: 16px;
            font-family: "Microsoft YaHei", sans-serif;
            background: #007bff;
            border-color: #0099ff;
            color: white;
            box-shadow: 0 2px 8px rgba(0,123,255,0.3);
        }

        .articles-container {
            display: grid;
            gap: 2px;
        }

        .article-card {
            background: #1a1a1a;
            padding: 2px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.25);
            border: 1px solid #2d2d2d;
        }

        .article-title {
            font-size: 16px;
            font-weight: 600;
            color: #31d3fb;
            margin-bottom: 2px;
            cursor: pointer;
            transition: color 0.3s;
            border-left: 4px solid #1677ff;
            padding-left: 12px;
        }

        .article-title:hover {
            color: #00f2ff;
        }

        .user-info {
            display: flex;
            align-items: flex-start;
            margin: 4px 0;
        }

        .avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            margin-right: 12px;
            object-fit: cover;
        }

        .user-meta {
            flex: 1;
            min-height: 35px;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }

        .meta-line {
            display: flex;
            align-items: baseline;
            gap: 2px;
            line-height: 1.2;
        }

        .nickname {
            font-size: 16px;
            font-weight: 600;
            color: #d0d0d0;
            margin-right: 8px;
        }
        .medal-badge {
            display: inline-flex;
            align-items: center;
            gap: 2px;
        }

    .medal-icon {
        width: 24px; /* 调整为更大的尺寸 */
        height: 24px;
        vertical-align: middle;
        margin-right: 4px; /* 增加间距避免拥挤 */
        display: inline-block;
        background-size: contain;
        background-repeat: no-repeat;
        background-position: center;
    }

        .style-str {
            font-size: 14px;
            color: #666;
        }

        .time-line {
            font-size: 12px;
            color: #FF1500;
            margin-top: 2px;
        }

        .content {
            font-size: 14px;
            color: #b0b0b0;
            line-height: 1.6;
            margin: 2px 0;
            cursor: pointer;
            transition: color 0.3s;
        }

        .content:hover {
            color: #0099ff;
        }

        .stock-list {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
            margin-top: 4px;
        }

        .stock-tag {
            padding: 2px 12px;
            background: rgba(0,123,255,0.15);
            border-radius: 4px;
            font-size: 14px;
            color: #f8ff35;
            cursor: pointer;
            border: 1px solid rgba(0,123,255,0.3);
            transition: all 0.3s;
        }

        .stock-tag:hover {
            background: #ff1500;
            color: white;
            border-color: transparent;
        }

        .loading-indicator,
        .empty-tip,
        .error-tip {
            padding: 20px;
            text-align: center;
            color: #909090;
            background: #1a1a1a;
            border-radius: 8px;
            margin: 20px 0;
            border: 1px solid #2d2d2d;
        }
        
        .category-btn.refresh-btn {
            background: #28a745;
            border-color: #34d058;
            color: white;
        }
        .category-btn.refresh-btn:hover {
            background: #22863a;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        .loading-spinner {
            display: inline-block;
            width: 24px;
            height: 24px;
            border: 3px solid rgba(255,255,255,0.1);
            border-left-color: #0099ff;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        .load-more {
            text-align: center;
            padding: 10px;
            color: #909090;
            cursor: pointer;
        }
/* WebKit 浏览器 */
::-webkit-scrollbar {
  width: 10px;
  height: 0;
}
::-webkit-scrollbar-track {
  background: #2a2a2a;
}
::-webkit-scrollbar-thumb {
  background: #555;
  border-radius: 4px;
  transition: background 0.3s;
}
::-webkit-scrollbar-thumb:hover {
  background: #777;
}

    </style>
</head>
<body>
    <div class="container">
        <div class="category-bar">
            <button class="category-btn" data-category="">全部</button>
            <button class="category-btn" data-category="102">个股</button>
            <button class="category-btn" data-category="97">题材</button>
            <button class="category-btn" data-category="96">纪要</button>
            <button class="category-btn" data-category="101">资讯</button>
            <button class="category-btn active" data-category="newest">最新帖</button>
            <button class="category-btn refresh-btn" id="refresh-btn">刷新</button>
        </div>
        <div id="status-indicator"></div>
        <div class="articles-container" id="articles-container"></div>
         <div id="load-more" class="load-more"></div>
    </div>

    <script>
        (function() {
            const API_URL = 'https://app.jiuyangongshe.com/jystock-app/api/v2/article/community';
            const TOKEN = 'a2749745c95bd3253352746d883188ac';
            const DEFAULT_AVATAR = '';
            const DEFAULT_MEDAL = '';
            
            let currentCategory = 'newest';
            let refreshTimer = null;
            const statusEl = document.getElementById('status-indicator');
            const loadMoreEl = document.getElementById('load-more');
            let start = 1;
            let isLoading = false;
            let hasMore = true;

            function showStatus(type, message) {
                const types = {
                    loading: {class: 'loading-indicator', html: `<div class="loading-spinner"></div> ${message}`},
                    empty: {class: 'empty-tip', html: message},
                    error: {class: 'error-tip', html: message}
                };
                const status = types[type] || types.error;
                statusEl.className = status.class;
                statusEl.innerHTML = status.html;
            }

            async function init() {
                bindCategoryEvents();
                bindLoadMore();
                await loadArticles();
                startAutoRefresh();
            }

            function bindCategoryEvents() {
                document.querySelectorAll('.category-btn:not(.refresh-btn)').forEach(btn => {
                    btn.addEventListener('click', async () => {
                        document.querySelectorAll('.category-btn').forEach(b => b.classList.remove('active'));
                        btn.classList.add('active');
                        currentCategory = btn.dataset.category;
                        start = 1; // 重置start
                        hasMore = true; // 重置hasMore
                        loadMoreEl.style.display = 'block'; // 显示加载更多
                        try {
                            await loadArticles(true); // 传递true表示重置
                        } catch (error) {
                            console.error(error);
                        }
                    });
                });

                document.getElementById('refresh-btn').addEventListener('click', async () => {
                    start = 1; // 重置start
                    hasMore = true; // 重置hasMore
                    loadMoreEl.style.display = 'block'; // 显示加载更多
                    try {
                        await loadArticles(true); // 传递true表示重置
                    } catch (error) {
                        console.error('刷新失败:', error);
                    }
                });
            }

            function bindLoadMore() {
                loadMoreEl.addEventListener('click', () => {
                    if (!isLoading && hasMore) {
                        loadArticles();
                    }
                });

                window.addEventListener('scroll', () => {
                    const { scrollTop, scrollHeight, clientHeight } = document.documentElement;
                    if (scrollTop + clientHeight >= scrollHeight - 100 && !isLoading && hasMore) {
                        loadArticles();
                    }
                });
            }

            async function loadArticles(reset = false) {
                if (isLoading || !hasMore) return;
                isLoading = true;

                try {
                    if (reset) {
                        document.getElementById('articles-container').innerHTML = '';
                        //showStatus('loading', '加载中...');
                    } else {
                       // loadMoreEl.textContent = '加载中...';
                    }

                    const timestamp = Date.now();
                    const baseParams = {
                        category_id: currentCategory === 'newest' ? '' : currentCategory,
                        limit: 15,
                        order: currentCategory === 'newest' ? 0 : 1,
                        start: start,
                        type: 0,
                        back_garden: 0
                    };
                    const requestParams = currentCategory === 'newest' ? 
                        { ...baseParams, is_newest: 1 } : 
                        baseParams;

                    const response = await fetch(API_URL, {
                        method: 'POST',
                        headers: {
                            'Accept': 'application/json',
                            'Content-Type': 'application/json',
                            'token': TOKEN,
                            'platform': '3',
                            'timestamp': timestamp.toString()
                        },
                        body: JSON.stringify(requestParams)
                    });

                    if (!response.ok) throw new Error(`HTTP ${response.status}`);
                    const result = await response.json();
                    if (result.errCode !== "0") throw new Error(result.msg);

                    const rawArticles = result.data?.result || [];
                    const normalArticles = rawArticles
                        .filter(article => Number(article?.is_top ?? 0) !== 1)
                        .map(article => ({
                            ...article,
                            title: article.title || '无标题',
                            content: article.content || '无内容',
                            create_time: article.create_time || new Date().toISOString(),
                            user: {
                                nickname: article.user?.nickname || '匿名用户',
                                style_str: article.user?.style_str || null,
                                avatar: article.user?.avatar || DEFAULT_AVATAR,
                                medal_count: article.user?.medal_count || 0
                            },
                            stock_list: article.stock_list?.map(stock => ({
                                name: stock.name || '未知股票',
                                code: stock.code || ''
                            })) || []
                        }));

                    if (normalArticles.length > 0) {
                        renderArticles(normalArticles, reset);
                        start++; // 成功加载后递增start
                        if (normalArticles.length < 15) {
                            hasMore = false;
                            loadMoreEl.textContent = '没有更多内容了';
                        } else {
                            //loadMoreEl.textContent = '加载更多...';
                        }
                    } else {
                        if (reset) {
                            showStatus('empty', '暂无相关文章');
                        }
                        hasMore = false;
                        loadMoreEl.textContent = '没有更多内容了';
                    }

                } catch (error) {
                    console.error('加载错误:', error);
                    showStatus('error', `加载失败: ${error.message}`);
                    loadMoreEl.textContent = '加载失败，点击重试';
                } finally {
                    isLoading = false;
                }
            }

            function renderArticles(articles, reset = false) {
                const container = document.getElementById('articles-container');
                
                if (reset) {
                    container.innerHTML = '';
                }
                
                articles.forEach(article => {
                    const articleEl = document.createElement('div');
                    articleEl.className = 'article-card';
                    
                    articleEl.innerHTML = `
                        <div class="article-title">${article.title}</div>
                        <div class="user-info">
                            <img src="${article.user.avatar}" 
                                class="avatar" 
                                alt="头像"
                                onerror="this.src='${DEFAULT_AVATAR}'">
                            <div class="user-meta">
                                <div class="meta-line">
                                    <div class="nickname">${article.user.nickname}</div>
                                    ${article.user.medal_count > 0 ? 
                                        `<div class="medal-badge">
                                            ${Array.from({length: Math.min(article.user.medal_count, 5)}, () => `
                                                <img src="${DEFAULT_MEDAL}" 
                                                    class="medal-icon"
                                                    alt="勋章">
                                            `).join('')}
                                        </div>` : ''
                                    }
                                    ${article.user.style_str ? 
                                        `<div class="style-str">${article.user.style_str}</div>` : ''
                                    }
                                </div>
                                <div class="time-line">
                                    ${formatTime(article.create_time)}
                                </div>
                            </div>
                        </div>
                        <div class="content">${truncateContent(article.content, 150)}</div>
                        ${renderStockList(article.stock_list)}
                    `;

                    bindArticleEvents(articleEl, article);
                    container.appendChild(articleEl);
                });
            }

            function bindArticleEvents(articleEl, article) {
                articleEl.querySelectorAll('.article-title, .content').forEach(el => {
                    el.addEventListener('click', () => {
                        window.location.href= (`http://www.treeid/dlghttps://www.jiuyangongshe.com/a/${article.article_id}&tdxmyietitle=${article.title}&tdxmyiewidth=1100&tdxmyieheight=894`);
                    } 
                );
                });

                articleEl.querySelectorAll('.stock-tag').forEach(tag => {
                    const code = tag.dataset.code;
                    code && tag.addEventListener('click', (e) => {
                        e.stopPropagation();
                        window.location.href = `http://www.treeid/code_${code}`;
                    });
                });
            }

            function renderStockList(stocks) {
                return stocks.length ? `
                    <div class="stock-list">
                        ${stocks.map(stock => {
                            const code = (stock.code.match(/\d+/g) || [''])[0];
                            return `<div class="stock-tag" data-code="${code}">${stock.name}</div>`;
                        }).join('')}
                    </div>
                ` : '';
            }

            function formatTime(timeStr) {
                try {
                    return new Date(timeStr).toLocaleString('zh-CN', {
                        year: 'numeric',
                        month: '2-digit',
                        day: '2-digit',
                        hour: '2-digit',
                        minute: '2-digit'
                    });
                } catch {
                    return '时间未知';
                }
            }

            function truncateContent(text, maxLength) {
                return text.length > maxLength ? 
                    text.substring(0, maxLength).replace(/\s+$/, '') + '...' : 
                    text;
            }

            function startAutoRefresh() {
                refreshTimer && clearInterval(refreshTimer);
                refreshTimer = setInterval(() => {
                    if (document.visibilityState === 'visible') {
                        start = 1;
                        loadArticles(true);
                    }
                }, 10000);
            }

            // 初始化
            init();
        })();
    </script>
</body>
</html>